package com.yuke.cloud.service.wmc.controller.frontend;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.constant.MQConstants;
import com.yuke.cloud.common.base.dto.MsgNotificationBody;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.mq.RabbitMetaMessage;
import com.yuke.cloud.common.core.mq.RabbitSender;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.omc.dto.OdsOrderDto;
import com.yuke.cloud.service.api.omc.dto.OdsOrderGoodsDto;
import com.yuke.cloud.service.api.omc.dto.OdsTeamSpecGoods;
import com.yuke.cloud.service.api.omc.dto.OdsTeamSpecIntentDto;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.api.opc.service.OpcSendNotifyFeignApi;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.exceptions.PmcBizException;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.wmc.dto.AssGoodsReturnDto;
import com.yuke.cloud.service.wmc.dto.WmsStoragePicDto;
import com.yuke.cloud.service.wmc.entity.*;
import com.yuke.cloud.service.wmc.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by zys on 2018/12/10.
 */
@Api(value = "WEB - AssGoodsReturnController", tags = "处理AssGoodsReturn相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@Slf4j
@RequestMapping("/ass/goods_return")
public class AssGoodsReturnController extends BaseController {
    @Resource
    private AssGoodsReturnService assGoodsReturnService;
    @Resource
    private WmsWarehouseShopService wmsWarehouseShopService;
    @Resource
    private WmsWarehouseGroupService wmsWarehouseGroupService;
    @Resource
    private WmsStockInService wmsStockInService;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private PmcFeignApi pmcFeignApi;
    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;
    @Resource
    private OpcSendNotifyFeignApi opcSendNotifyFeignApi;
    @Resource
    private WmsWarehouseService wmsWarehouseService;
    @Resource
    private WmsStorageService wmsStorageService;
    @Resource
    private WmsStorageRecordService wmsStorageRecordService;
    @Autowired
    private RabbitSender rabbitSender;


    /**
     * 用户进行退货、退款请求
     * @param jsonObject
     * @return
     */
    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "assGoodsReturn", value = "该数据记录的POJO") @RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);

        Long orderid = Long.valueOf(jsonObject.get("orderid").toString());
        OdsOrderDto getbyid = omcOrderFeignApi.getOrderAndGoodsByOrderId(orderid);
        if (getbyid == null) {
            throw new RuntimeException("未找到订单信息，添加失败");
        }
        if (getbyid.getOrderStatus().toString().equals("3")){
            return WrapMapper.error("该订单已取消，不能退货！");
        }

        // add by wg 20190327 增加商品是否支持退款及退款时间的判断
//        if (getbyid.getIsCheckout()) {  // 已向家结算的商品不退货
//            return WrapMapper.error("该订单商品已过退货时间，无法申请退货");
//        }

        if (jsonObject.get("number") == null || Integer.valueOf(jsonObject.get("number").toString()).equals(0) ){
            return WrapMapper.error("退货数量不能为0，或参数错误！");
        }
        Date sendTime = getbyid.getSendTime();
        // add by wg 20190727
        if (sendTime == null || PublicUtil.isEmpty(sendTime)) {
            sendTime = getbyid.getCreateTime();
        }
        if (jsonObject.get("specid") == null || jsonObject.get("specid").toString().equals("0")){
            return WrapMapper.error("参数错误！商品ID未获取到");
        }
        // add by wg 20190327 增加商品是否支持退款及退款时间的判断
        Long specId = Long.valueOf(jsonObject.get("specid").toString());


        WmsStoragePicDto wmsStoragePicDto = new WmsStoragePicDto();
        wmsStoragePicDto.setSpecId(specId);
        wmsStoragePicDto.setWarehouseId(getbyid.getWarehouseId());
        List<WmsStorage> wmsStorageList = wmsStorageService.getWmsStorageByPic(wmsStoragePicDto);
        if (wmsStorageList == null || wmsStorageList.size() < 1) {
            log.error("--- pmcFeignApi.getSpecInfoDtoBySpecId(specId)内部异常，参数：{} ---",specId);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }

        if (!wmsStorageList.get(0).getIsReturn()) {
            return WrapMapper.error("该商品不支持退货");
        }
        // 20200724 退货时间暂时不考虑
//        Date now = new Date();
//        if (sendTime != null && (now.getTime() - sendTime.getTime()) > Long.parseLong(wmsStorageList.get(0).getReturnPeriod().toString()) * 24 * 3600 * 1000) {
//            return WrapMapper.error("该商品仅支持" + wmsStorageList.get(0).getReturnPeriod() + "天内退货，已过退货时间，无法申请退货");
//        }

        // add by wg 20190325 如果订单下的商品已经有了退货记录，如果再提交则直接进行更新
        Example example1 = new Example(AssGoodsReturn.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId", getbyid.getOrderId());
        criteria1.andEqualTo("orderGoodsId",specId);

        List<AssGoodsReturn> listExist = assGoodsReturnService.selectByExample(example1);
        if (listExist != null && listExist.size() > 0) {
            if (listExist.get(0).getReturnStatus().equals((byte)5) || listExist.get(0).getReturnStatus().equals((byte)7)){
                logger.info("该商品已申请退货或已完成退货，无法再申请,orderId={}, specId={}", getbyid.getOrderId(), jsonObject.get("specid").toString());
                return WrapMapper.error("该商品已申请退货或已完成退货，无法再申请");
            }
        }
        //如果订单未发货，未打印订单，退货直接入库
        //如果订单已发货，无论是否收到货，退货必须生成退货单，并审核。
        // 未收货时，商品由司机带回入库
        //已收货时，须通过客服审核成功才能由司机带回入库，并协商退款。
        AssGoodsReturn assGoodsReturn = new AssGoodsReturn();
        assGoodsReturn.setOrderId(orderid);
        assGoodsReturn.setNumber(Integer.valueOf(jsonObject.get("number").toString()));
        assGoodsReturn.setOrderGoodsId(specId);

        //未发货
        if (getbyid.getShippingStatus() < 2) {

            //1.把订单商品信息更新
            updateOrderInfo(getbyid,assGoodsReturn);
            //2.把库存信息更新
            updateWmsStorage(getbyid,assGoodsReturn);

            return WrapMapper.ok("该商品未发货（未打印出货单），直接退库存。");
        } else {
            //已发货
            assGoodsReturn.setReturnStatus((byte) 5);
            assGoodsReturn.setShopId(getbyid.getShopId());
            assGoodsReturn.setUserId(getbyid.getUserId());
            assGoodsReturn.setOrderType(getbyid.getOrderType());
            assGoodsReturn.setCreateTime(new Date());
            assGoodsReturn.setIsRefund(false);

            assGoodsReturn.setRefundPayable(Integer.valueOf(jsonObject.get("refundamount").toString()));


            if (jsonObject.get("returnreason") != null) {
                String s1 = jsonObject.get("returnreason").toString();
                switch (s1) {
                    case "0":
                        assGoodsReturn.setReturnReason((byte) 0);
                        break;
                    case "1":
                        assGoodsReturn.setReturnReason((byte) 1);
                        break;
                    case "2":
                        assGoodsReturn.setReturnReason((byte) 2);
                        break;
                    case "3":
                        assGoodsReturn.setReturnReason((byte) 3);
                        break;
                    case "4":
                        assGoodsReturn.setReturnReason((byte) 4);
                        break;
                    case "5":
                        assGoodsReturn.setReturnReason((byte) 5);
                        break;
                    case "6":
                        assGoodsReturn.setReturnReason((byte) 6);
                        break;
                    case "7":
                        assGoodsReturn.setReturnReason((byte) 7);
                        break;
                }

            }

            assGoodsReturn.setGoodsReturnId(generateId());

            // add by wg 20190407 增加备注
            String remarkUser = "";
            if (PublicUtil.isNotEmpty(jsonObject.get("customReturnReason"))) {
                remarkUser = jsonObject.get("customReturnReason").toString();
            }
            assGoodsReturn.setRemarkUser(remarkUser);

            assGoodsReturnService.save(assGoodsReturn);

            List<OdsOrderGoodsDto>  odsOrderGoodsDtos = getbyid.getGoodList();
            for (OdsOrderGoodsDto item : odsOrderGoodsDtos){
                if (item.getSpecId().equals(specId)){
                    item.setGoodsStatus((byte)2);
                    Integer rr = omcOrderFeignApi.updateOrderGoods(item);
                    System.out.println(rr);
                }

            }
        }



        Boolean isNotifyWare = true;
        // add by wg 20190322 应根据订单类型进行处理，如果是店铺订单则直接发websocket通知管理员处理，如果是用户订单则通知店铺处理
        if (getbyid.getOrderType() == 1) {  // 用户订单
            MsgNotificationBody msg = new MsgNotificationBody();
            msg.setTitle("退款/退货申请");
            msg.setContent("订单" + orderid + "申请退款/退货，请处理");
            msg.setTime(new Date());
            msg.setReceiveType((byte) 1);
            msg.setOrderType((byte) 1);
            msg.setMsgType("orderMsg");
            Long shopId = getbyid.getShopId();
            List<Long> list = new ArrayList<>();
            list.add(shopId);
            List<ShopInfoDto> shopInfoByShopIds = smcFeignApi.getShopUserIdByShopIds(list);
            // mod by wg 20190518 改成只有云顶店铺配送的商品才通知店铺，由店铺去处理退款
//            if (shopInfoByShopIds != null && shopInfoByShopIds.size() != 0) {
            if (getbyid.getShippingType() == 3 && shopInfoByShopIds != null && shopInfoByShopIds.size() != 0) {
                msg.setOrderType((byte) 3);
                isNotifyWare = false;
                System.out.println(shopInfoByShopIds.get(0).getUserId().toString());
                opcSendNotifyFeignApi.sendnotify(shopInfoByShopIds.get(0).getUserId().toString(), "退款/退货申请", JSON.toJSONString(msg), 1);
                opcSendNotifyFeignApi.sendnotify(shopInfoByShopIds.get(0).getUserId().toString(), "退款/退货申请", "订单" + orderid + "申请退款，请处理", 0);
            }
        }


        if (isNotifyWare) {
            // 通知管理员处理
            Map map = new HashMap();
            map.put("MessageType", "findWarehouseAdmin");
            map.put("shopIds", getbyid.getShopId().toString());
            if (getbyid.getWarehouseId() != null) {
                map.put("warehouseIds", getbyid.getWarehouseId().toString());
            }
            map.put("body", "通知仓库管理员，有退款/退货申请需要审核");
            RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();
            rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
            rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_WMC);
            rabbitMetaMessage.setPayload(JSON.toJSONString(map));
            try {
                rabbitSender.send(rabbitMetaMessage);
            } catch (Exception e) {
                log.error("rabbitSender.send()调用异常");
            }
        }

        return WrapMapper.ok();
    }
    //退货，修改订单信息
    private Wrapper<Integer> updateOrderInfo(OdsOrderDto odsOrderDto, AssGoodsReturn assGoodsReturn){

        List<OdsOrderGoodsDto>  odsOrderGoodsDtos = odsOrderDto.getGoodList();
        for (OdsOrderGoodsDto item : odsOrderGoodsDtos){
            if (item.getSpecId().equals(assGoodsReturn.getOrderGoodsId())){
                if (item.getGoodsNum().equals(assGoodsReturn.getNumber())){
                    item.setGoodsNum(0);
                    item.setGoodsPrice(0);
                    item.setGoodsWeight(0);
                    item.setPayPrice(0);
                    item.setGoodsStatus((byte)3);
                }else if (item.getGoodsNum() > assGoodsReturn.getNumber()){
                    item.setGoodsNum(item.getGoodsNum() - assGoodsReturn.getNumber());
                    item.setGoodsStatus((byte)0);
                }else {
                    return WrapMapper.error("订单商品数量信息错误！");
                }
                Integer rr = omcOrderFeignApi.updateOrderGoods(item);

            }

        }
        System.out.println("修改后的订单信息："+ odsOrderDto);
        Long groupId=wmsWarehouseGroupService.findGroupId(odsOrderDto.getShopId());
        odsOrderDto.setGroupId(groupId);
        omcOrderFeignApi.countMoneyAndUpdate(odsOrderDto);
        // 把订单金额信息更新
//        OdsOrderDto orderDto = new OdsOrderDto();
//        orderDto.setOrderId(odsOrderDto.getOrderId());
//        orderDto.setAmountPayable(totlePayPrice);
//        orderDto.setProductPriceTotal(totlePrice);
//        orderDto.setDiscount(totlePrice - totlePayPrice);
//        Integer yy = omcOrderFeignApi.updateOrderPay(orderDto);
        return WrapMapper.ok(1);
    }

    //退货修改库存信息
    private Wrapper<Integer> updateWmsStorage(OdsOrderDto odsOrderDto, AssGoodsReturn assGoodsReturn){
        WmsStorage wmsStorage = new WmsStorage();
        wmsStorage.setWarehouseId(odsOrderDto.getWarehouseId());
        wmsStorage.setSpecId(assGoodsReturn.getOrderGoodsId());
        List<WmsStorage> wmsStorageList = wmsStorageService.select(wmsStorage);
        if (wmsStorageList != null && wmsStorageList.size() > 0){
            wmsStorage = wmsStorageList.get(0);


            //如果订单为已发货，修改number,salecount,同时，生成商品入库操作，修改库存记录操作
            if (odsOrderDto.getShippingStatus() > 1){
                wmsStorage.setNumber(wmsStorage.getNumber()+assGoodsReturn.getNumber());
                wmsStorage.setSaleCount(wmsStorage.getSaleCount()- assGoodsReturn.getNumber()>0?wmsStorage.getSaleCount() - assGoodsReturn.getNumber() : 0);

                //生成商品入库操作
                WmsStockIn wmsStockIn = new WmsStockIn();
                wmsStockIn.setGoodsReturnId(assGoodsReturn.getGoodsReturnId());
                wmsStockIn.setInType((byte)2);
                wmsStockIn.setWarehouseId(wmsStorage.getWarehouseId());
                wmsStockIn.setMfgDate(wmsStorage.getMfgDate());
                wmsStockIn.setSpecId(wmsStorage.getSpecId());
                wmsStockIn.setProductId(wmsStorage.getProductId());
                wmsStockIn.setInNumber(assGoodsReturn.getNumber());
                System.out.println("wmsStockIn="+wmsStockIn);
                wmsStockInService.save(wmsStockIn);
            }else{
                //如果订单未发货，只修改locknumber
                wmsStorage.setLockNumber(wmsStorage.getLockNumber() - assGoodsReturn.getNumber()>0?wmsStorage.getLockNumber() - assGoodsReturn.getNumber() : 0);
            }
            wmsStorageService.update(wmsStorage);


        }
        //修改库存记录
        WmsStorageRecord wmsStorageRecord = new WmsStorageRecord();
        wmsStorageRecord.setWarehouseId(odsOrderDto.getWarehouseId());
        wmsStorageRecord.setSpecId(assGoodsReturn.getOrderGoodsId());

        wmsStorageRecordService.updateRecorder(wmsStorageRecord,assGoodsReturn.getNumber());

        return WrapMapper.ok(1);
    }


    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        assGoodsReturnService.deleteById(id);
        return WrapMapper.ok();
    }

    //供质检同不同意退货处理
    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "assGoodsReturn", value = "需要修改的内容") @RequestBody AssGoodsReturn assGoodsReturn) {
        //todo 质检同意不同意都要通过信鸽发送消息告诉用户
        MsgNotificationBody msg = new MsgNotificationBody();
        msg.setTitle("退款/退货通知");

        if (assGoodsReturn.getReturnStatus().toString().equals("3")) {
            msg.setContent("您的订单" + assGoodsReturn.getOrderId() + "退款/退货请求被拒绝：商品检验不通过");
            msg.setTime(new Date());
            msg.setReceiveType((byte) 1);
//            msg.setOrderType((byte) 1);
            msg.setMsgType("orderMsg");
            opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款/退货请求被拒绝", "您的订单" + assGoodsReturn.getOrderId() + "退款/退货请求被拒绝：商品检验不通过", 0);
            opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款/退货请求被拒绝", JSON.toJSONString(msg), 1);
        } else if (assGoodsReturn.getReturnStatus().toString().equals("7")) {
            msg.setContent("您的订单" + assGoodsReturn.getOrderId() + "退款/退货请求被拒绝");
            msg.setTime(new Date());
            msg.setReceiveType((byte) 1);
//            msg.setOrderType((byte) 1);
            msg.setMsgType("orderMsg");
            opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款/退货请求被拒绝", "您的订单" + assGoodsReturn.getOrderId() + "退款/退货请求被拒绝", 0);
            opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款/退货请求被拒绝", JSON.toJSONString(msg), 1);
        } else {
            // add by wg 20190518 增加根据不同的订单类型进行不同的处理
            // 1.获取订单信息
            OdsOrderDto odsOrderDto =  omcOrderFeignApi.getOrderAndGoodsByOrderId(assGoodsReturn.getOrderId());
            if (odsOrderDto == null) {
                return WrapMapper.error("无法获取订单信息");
            }
            assGoodsReturn.setUserId(odsOrderDto.getUserId());

            //1.把订单商品信息更新
            updateOrderInfo(odsOrderDto,assGoodsReturn);
            //2.把库存信息更新
            updateWmsStorage(odsOrderDto,assGoodsReturn);

            String strConent = "";
            if (odsOrderDto.getIsFactory()) {
                // 获取店铺信息
                List<ShopInfoDto> shopInfoDtos = smcFeignApi.getShopInfoByShopIds(Collections.singletonList(odsOrderDto.getFactoryShopId()));
                if (shopInfoDtos == null || shopInfoDtos.size() <= 0) {
                    return WrapMapper.error("无法获取厂家直销店铺信息");
                }
                Map mapAddress = wmsWarehouseService.getaddressbyregionid(shopInfoDtos.get(0).getRegionCountyId());

                if (mapAddress == null) {
                    return WrapMapper.error("无法获取地址信息");
                }

                String address = mapAddress.get("regionProvinceName").toString()
                        +  mapAddress.get("regionCityName").toString()
                        +  mapAddress.get("regionCountyName").toString()
                        +  shopInfoDtos.get(0).getAddress();

                strConent = "您的订单" + assGoodsReturn.getOrderId() + "退款/退货请求已确认，请牢记退款单号：" + assGoodsReturn.getGoodsReturnId()
                        + ", 并将商品寄往：" + address + "，联系电话：" + shopInfoDtos.get(0).getMobile();
            } else {
                strConent = "您的订单" + assGoodsReturn.getOrderId() + "退款/退货请求已确认，请牢记退款单号：" + assGoodsReturn.getGoodsReturnId();
            }

            msg.setContent(strConent);
            msg.setTime(new Date());
            msg.setReceiveType((byte) 1);
//                msg.setOrderType((byte) 1);
            msg.setMsgType("orderMsg");
            opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款请求已确认", strConent, 0);
            opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款请求已确认", JSON.toJSONString(msg), 1);
        }

        assGoodsReturn.setUpdateTime(new Date());
        int update = assGoodsReturnService.update(assGoodsReturn);

        return WrapMapper.ok(update);
    }


    //供商家同不同意退货处理
    @PostMapping("/update67")
    @ApiOperation(httpMethod = "POST", value = "修改一条记录")
    public Wrapper update1(@RequestBody AssGoodsReturn assGoodsReturn) {
        System.out.println(assGoodsReturn.getReturnStatus());
        //todo 商家不同意都要通过信鸽发送消息告诉用户
        if (assGoodsReturn.getReturnStatus() != null) {
            MsgNotificationBody msg = new MsgNotificationBody();
            msg.setTitle("退款通知");
            if (assGoodsReturn.getReturnStatus().intValue() == 7) {
                msg.setContent("您的订单" + assGoodsReturn.getOrderId() + "退款请求被拒绝");
                msg.setTime(new Date());
                msg.setReceiveType((byte) 1);
//                msg.setOrderType((byte) 1);
                msg.setMsgType("orderMsg");
                opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款请求被拒绝(店铺拒绝)", "您的订单" + assGoodsReturn.getOrderId() + "退款请求被拒绝", 0);
                opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款请求被拒绝(店铺拒绝)", JSON.toJSONString(msg), 1);
            } else {
                msg.setContent("您的订单" + assGoodsReturn.getOrderId() + "退款请求已确认，请牢记退款单号：" + assGoodsReturn.getGoodsReturnId());
                msg.setTime(new Date());
                msg.setReceiveType((byte) 1);
//                msg.setOrderType((byte) 1);
                msg.setMsgType("orderMsg");
                opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款请求已确认", "您的订单" + assGoodsReturn.getOrderId() + "退款请求已确认，请牢记退款单号：" + assGoodsReturn.getGoodsReturnId(), 0);
                opcSendNotifyFeignApi.sendnotify(assGoodsReturn.getUserId().toString(), "退款请求已确认", JSON.toJSONString(msg), 1);
            }
        }

        assGoodsReturn.setUpdateTime(new Date());
        int update = assGoodsReturnService.update(assGoodsReturn);
        return WrapMapper.ok(update);
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<AssGoodsReturn> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        AssGoodsReturn assGoodsReturn = assGoodsReturnService.findById(id);
        return WrapMapper.ok(assGoodsReturn);
    }

    @GetMapping("/getDetail")
    @ApiOperation(httpMethod = "GET", value = "获取单个记录")
    public Wrapper getit(@ApiParam(name = "goodsReturnId", value = "退货单id", defaultValue = "0") @RequestParam(required = false) Long goodsReturnId) {
        Example example = new tk.mybatis.mapper.entity.Example(AssGoodsReturn.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("goodsReturnId", goodsReturnId);
        List<AssGoodsReturn> list = assGoodsReturnService.selectByExample(example);

        return WrapMapper.ok(list);
    }


    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<AssGoodsReturn>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                  @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "20") Integer size,
                                                  @ApiParam(name = "goodsReturnId", value = "退货单id", defaultValue = "0") @RequestParam(required = false) Long goodsReturnId,
                                                  @ApiParam(name = "orderId", value = "订单id", defaultValue = "0") @RequestParam(required = false) Long orderId,
                                                  @ApiParam(name = "warehouseId", value = "仓库名称", defaultValue = "0") @RequestParam(required = false) Long warehouseId,
                                                  @ApiParam(name = "shopName", value = "商品名称", defaultValue = "0") @RequestParam(required = false) String shopName,
                                                  @ApiParam(name = "beginTime", value = "开始时间", defaultValue = "0") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date beginTime,
                                                  @ApiParam(name = "endTime", value = "结束时间", defaultValue = "0") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date endTime) {

        Example example;
        if (goodsReturnId != null && !goodsReturnId.equals("")) {
            example = new tk.mybatis.mapper.entity.Example(AssGoodsReturn.class);
            Example.Criteria criteria = example.createCriteria();
            System.out.println("goodsReturnId" + goodsReturnId);
            criteria.andEqualTo("goodsReturnId", goodsReturnId);
        }else {
            PageHelper.startPage(page, size);
            example = new tk.mybatis.mapper.entity.Example(AssGoodsReturn.class);
            Example.Criteria criteria = example.createCriteria();
            List<Byte> list8 = new ArrayList<>();
            list8.add((byte) 3);
            list8.add((byte) 4);
            list8.add((byte) 7);
            criteria.andNotIn("returnStatus", list8);
            List<Byte> list10 = new ArrayList();
            list10.add((byte) 6);
            list10.add((byte) 5);
            list10.add((byte) 2);
            criteria.orIn("returnStatus", list10);
            example.setOrderByClause("create_time desc");
            if (warehouseId != null && !warehouseId.equals("")) {
                Example example1 = new Example(WmsWarehouseShop.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("warehouseId", warehouseId);
                List<WmsWarehouseShop> wmsWarehouseShops = wmsWarehouseShopService.selectByExample(example1);
                if (wmsWarehouseShops.size() == 0) {
                    List<AssGoodsReturn> returnlist = new ArrayList<>();
                    PageInfo pageInfo = new PageInfo(returnlist);
                    return WrapMapper.ok(pageInfo);
                }
                List<Long> list1 = new ArrayList<>();
                for (WmsWarehouseShop wmsWarehouseShop : wmsWarehouseShops) {
                    list1.add(wmsWarehouseShop.getShopId());
                }
                criteria.andIn("shopId", list1);
            }

            if (orderId != null && !orderId.equals("")) {
                System.out.println("进入orderid" + orderId);
                criteria.andEqualTo("orderId", orderId);
            }
            if (shopName != null && !shopName.equals("")) {
                List<Long> shopIdsShopName = smcFeignApi.getShopIdsShopName(shopName);
                if (shopIdsShopName != null || shopIdsShopName.size() != 0) {
                    criteria.andIn("shopId", shopIdsShopName);
                }
            }
            if (beginTime != null && !beginTime.equals("")) {
                criteria.andLessThanOrEqualTo("createTime", endTime);
                criteria.andGreaterThanOrEqualTo("createTime", beginTime);

            }
        }
        PageHelper.startPage(page, size);
        List<AssGoodsReturn> list = assGoodsReturnService.selectByExample(example);

        if (list.size() == 0) {
            List<AssGoodsReturn> returnlist = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(returnlist);
            return WrapMapper.ok(pageInfo);
        }
        //店铺id集合
        StringBuilder sb = new StringBuilder();
        List<Long> list2 = new ArrayList<>();
        List<Long> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getOrderId());
            list1.add(list.get(i).getShopId());
            // mod by wg 20190423
//            if (i != list.size()) {
            if (i != (list.size() - 1)) {
                sb.append(list.get(i).getOrderGoodsId().toString()).append(",");
            } else {
                sb.append(list.get(i).getOrderGoodsId().toString());
            }
        }
        List<OdsOrderDto> odsOrderDtos = omcOrderFeignApi.getbyidS(list2);
        System.out.println("订单信息："+odsOrderDtos);
        if (odsOrderDtos == null || odsOrderDtos.size() == 0) {
            List<AssGoodsReturn> returnlist = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(returnlist);
            return WrapMapper.ok(pageInfo);
        }
        //商品规格
        System.out.println("商品规格id是"+sb.toString());
        List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(sb.toString());
        System.out.println("返回的商品信息是"+specInfoDtosBySpecIds.get(0).getSpecName());
        if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
            List<AssGoodsReturn> returnlist = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(returnlist);
            return WrapMapper.ok(pageInfo);
        }

        //店铺信息
        System.out.println("店铺id" + list1);
        List<ShopInfoDto> shopInfoByShopIds = smcFeignApi.getShopInfoByShopIds(list1);

        if (shopInfoByShopIds == null || shopInfoByShopIds.size() == 0) {
            List<AssGoodsReturn> returnlist = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(returnlist);
            return WrapMapper.ok(pageInfo);
        }

        System.out.println("返回的店铺信息" + shopInfoByShopIds.get(0).getShopName());
        //仓库信息
        System.out.println("店铺id" + list1);
        List<Map> wmsWarehouses = wmsWarehouseShopService.getwarehousebyshopid(list1);
        System.out.println("返回的仓库信息" + wmsWarehouses.get(0));
        if (wmsWarehouses == null || wmsWarehouses.size() == 0) {
            List<AssGoodsReturn> returnlist = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(returnlist);
            return WrapMapper.ok(pageInfo);
        }
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < specInfoDtosBySpecIds.size(); j++) {
                for (int k = 0; k < shopInfoByShopIds.size(); k++) {
                    for (int g = 0; g < wmsWarehouses.size(); g++) {
                        for (int i6 = 0; i6 < odsOrderDtos.size(); i6++) {
                            AssGoodsReturn assGoodsReturn = list.get(i);
                            if (assGoodsReturn.getUserId().toString().equals(odsOrderDtos.get(i6).getUserId().toString()) && assGoodsReturn.getShopId().toString().equals(shopInfoByShopIds.get(k).getShopId().toString()) && assGoodsReturn.getShopId().toString().equals(wmsWarehouses.get(g).get("shop_id").toString()) && assGoodsReturn.getOrderGoodsId().toString().equals(specInfoDtosBySpecIds.get(j).getSpecId().toString())) {
                                assGoodsReturn.setSpecName(specInfoDtosBySpecIds.get(j).getSpecName());
                                assGoodsReturn.setShopName(shopInfoByShopIds.get(k).getShopName());
                                assGoodsReturn.setWarehouseName(wmsWarehouses.get(g).get("warehouse_name").toString());
                                assGoodsReturn.setUserName(odsOrderDtos.get(i6).getUserName());
                                assGoodsReturn.setPayType(odsOrderDtos.get(i6).getPayType());
                            }
                        }
                    }
                }
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 后台管理系统进行退款操作
     * @param orderId
     * @param refund
     * @param goodsReturnId
     * @return
     */
    @GetMapping("/refund")
    public Wrapper refund(@RequestParam("orderId") Long orderId,
                          @RequestParam("refund") double refund,
                          @RequestParam("goodsReturnId") Long goodsReturnId) {
        System.out.println(refund);
        Map map = new HashMap();
        map.put("orderId", orderId);
        map.put("refund_amount", refund);
        map.put("goodsReturnId", goodsReturnId);
        int redund = omcOrderFeignApi.redund(map);
        if (redund == 1) {
//            System.err.println("退款成功++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");//修改退款单状态为已经退款
            //同时修改订单状态为已经退款
            int i = omcOrderFeignApi.changetorefund(orderId, refund);
            // mod by wg 20190325
//            AssGoodsReturn assGoodsReturn = new AssGoodsReturn().setOrderId(orderId);
//            List<AssGoodsReturn> select = assGoodsReturnService.select(assGoodsReturn);
//            Long goodsReturnId = select.get(0).getGoodsReturnId();
//            assGoodsReturn.setIsRefund(true);
//            double v = refund; // * 100;
//            assGoodsReturn.setRefundPaid((int) v);
//            assGoodsReturn.setGoodsReturnId(goodsReturnId);
            if (goodsReturnId != null) {
                AssGoodsReturn assGoodsReturn = new AssGoodsReturn();
                assGoodsReturn.setGoodsReturnId(goodsReturnId);
                assGoodsReturn.setIsRefund(true);
                double v = refund; // * 100;
                assGoodsReturn.setRefundPaid((int) v);
                assGoodsReturn.setUpdateTime(new Date());
                assGoodsReturnService.update(assGoodsReturn);
            }

            return WrapMapper.ok("退款成功");
        } else if(redund == 0) {
            return WrapMapper.ok("退款失败:未知支付方式，无法在线原路退款");
        } else {
            return WrapMapper.ok("退款失败");
        }

    }

    @PostMapping("/batchReturn")
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper batchReturn(@ApiParam(name = "assGoodsReturn", value = "该数据记录的POJO") @RequestBody JSONObject jsonObject) {
        if (jsonObject == null || jsonObject.get("specInfo") == null){
            return WrapMapper.error("参数错误！");
        }

        JSONArray ts = jsonObject.getJSONArray("specInfo");
        System.out.println(ts.toString());
        for(int i = 0, n = ts.size();i<n;i++){
            JSONObject json = JSONObject.parseObject(ts.get(i).toString());
            json.put("orderid",jsonObject.get("orderid"));
//            json.put("refundamount",jsonObject.get("refundamount"));
//            json.put("returnreason",jsonObject.get("returnreason"));
//            json.put("customReturnReason",jsonObject.get("customReturnReason"));
            this.add(json);
        }

        return WrapMapper.ok("提交成功！");
    }

    @PostMapping("/selectByCondition")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<PageInfo<AssGoodsReturn>> selectByCondition(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                  @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "20") Integer size,
                                                  @ApiParam(name = "goodsReturnId", value = "退货单id", defaultValue = "0") @RequestBody(required = false) AssGoodsReturnDto assGoodsReturnDto) {
        System.out.println(assGoodsReturnDto);
        PageHelper.startPage(page, size);
        List<AssGoodsReturn> list = assGoodsReturnService.selectByCondition(assGoodsReturnDto);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }


    /**
     * 用户进行退货、退款请求
     * @param jsonObject
     * @return
     */
    @PostMapping("/teamReturn")
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper addTeamIntent(@ApiParam(name = "assGoodsReturn", value = "该数据记录的POJO") @RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);

        Long intentId = Long.valueOf(jsonObject.get("intentId").toString());
        OdsTeamSpecIntentDto odsTeamSpecIntentDto = new OdsTeamSpecIntentDto();
        odsTeamSpecIntentDto.setIntentId(intentId);
        Wrapper<List<OdsTeamSpecIntentDto>> wrapper = omcOrderFeignApi.selectTeamIntentByCondition(odsTeamSpecIntentDto);
        if (wrapper.getCode() != 200) {
            throw new RuntimeException("未找到团购订单信息，添加失败");
        }
        OdsTeamSpecIntentDto odsTeamIntentDto = wrapper.getResult().get(0);
        if (odsTeamIntentDto.getIntentStatus().toString().equals("3")){
            return WrapMapper.error("该订单已取消，不能退货！");
        }

        if (jsonObject.get("number") == null || Integer.valueOf(jsonObject.get("number").toString()).equals(0) ){
            return WrapMapper.error("退货数量不能为0，或参数错误！");
        }

        if (jsonObject.get("specId") == null || jsonObject.get("specId").toString().equals("0")){
            return WrapMapper.error("参数错误！商品ID未获取到");
        }
        // add by wg 20190327 增加商品是否支持退款及退款时间的判断
        Long specId = Long.valueOf(jsonObject.get("specId").toString());

        WmsStoragePicDto wmsStoragePicDto = new WmsStoragePicDto();
        wmsStoragePicDto.setSpecId(specId);
        wmsStoragePicDto.setWarehouseId(odsTeamIntentDto.getWarehouseId());
        List<WmsStorage> wmsStorageList = wmsStorageService.getWmsStorageByPic(wmsStoragePicDto);
        if (wmsStorageList == null || wmsStorageList.size() < 1) {
            log.error("--- pmcFeignApi.getSpecInfoDtoBySpecId(specId)内部异常，参数：{} ---",specId);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }

        if (!wmsStorageList.get(0).getIsReturn()) {
            return WrapMapper.error("该商品不支持退货");
        }
        // 20200724 退货时间暂时不考虑
//        Date now = new Date();
//        if (sendTime != null && (now.getTime() - sendTime.getTime()) > Long.parseLong(wmsStorageList.get(0).getReturnPeriod().toString()) * 24 * 3600 * 1000) {
//            return WrapMapper.error("该商品仅支持" + wmsStorageList.get(0).getReturnPeriod() + "天内退货，已过退货时间，无法申请退货");
//        }

        // add by wg 20190325 如果订单下的商品已经有了退货记录，如果再提交则直接进行更新
        Example example1 = new Example(AssGoodsReturn.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId", odsTeamIntentDto.getIntentId());
        criteria1.andEqualTo("orderGoodsId",specId);
        List<AssGoodsReturn> listExist = assGoodsReturnService.selectByExample(example1);

        if (listExist != null && listExist.size() > 0) {
            if (listExist.get(0).getReturnStatus().equals((byte)5) || listExist.get(0).getReturnStatus().equals((byte)7)){
                logger.info("该商品已申请退货或已完成退货，无法再申请,orderId={}, specId={}",odsTeamIntentDto.getIntentId(), jsonObject.get("specId").toString());
                return WrapMapper.error("该商品已申请退货或已完成退货，无法再申请");
            }
        }
        //如果订单未发货，未打印订单，退货直接入库
        //如果订单已发货，无论是否收到货，退货必须生成退货单，并审核。
        // 未收货时，商品由司机带回入库
        //已收货时，须通过客服审核成功才能由司机带回入库，并协商退款。
        AssGoodsReturn assGoodsReturn = new AssGoodsReturn();
        assGoodsReturn.setOrderId(odsTeamIntentDto.getIntentId());
        assGoodsReturn.setNumber(Integer.valueOf(jsonObject.get("number").toString()));
        assGoodsReturn.setOrderGoodsId(specId);

        //未发货
        if (odsTeamIntentDto.getShippingStatus() < 2) {

            //1.把订单商品信息更新
           // updateOrderInfo(odsTeamIntentDto,assGoodsReturn);
            //2.把库存信息更新
            //updateWmsStorage(odsTeamIntentDto,assGoodsReturn);

            return WrapMapper.ok("该商品未发货（未打印出货单），直接退库存。");
        } else {
            //已发货
            assGoodsReturn.setReturnStatus((byte) 5);
            assGoodsReturn.setShopId(odsTeamIntentDto.getShopId());
            assGoodsReturn.setUserId(odsTeamIntentDto.getUserId());
            assGoodsReturn.setOrderType(odsTeamIntentDto.getIntentType());
            assGoodsReturn.setCreateTime(new Date());
            assGoodsReturn.setIsRefund(false);

            assGoodsReturn.setRefundPayable(Integer.valueOf(jsonObject.get("refundamount").toString()));


            if (jsonObject.get("returnreason") != null) {
                String s1 = jsonObject.get("returnreason").toString();
                assGoodsReturn.setReturnReason(Byte.parseByte(s1));
            }

            assGoodsReturn.setGoodsReturnId(generateId());


            String remarkUser = "";
            if (PublicUtil.isNotEmpty(jsonObject.get("customReturnReason"))) {
                remarkUser = jsonObject.get("customReturnReason").toString();
            }

            String picUrl = "";
            if (PublicUtil.isNotEmpty(jsonObject.get("picUrl"))) {
                picUrl = jsonObject.get("picUrl").toString();
            }
            assGoodsReturn.setPicUrl(picUrl);

            assGoodsReturnService.save(assGoodsReturn);

            List<OdsTeamSpecGoods>  odsTeamSpecGoods = odsTeamIntentDto.getTeamGoodsList();
            for (OdsTeamSpecGoods item : odsTeamSpecGoods){
                if (item.getSpecId().equals(specId)){
                    item.setGoodsStatus((byte)2);
                    Integer rr = omcOrderFeignApi.updateIntentGoods(item);
                    System.out.println(rr);
                }

            }
        }



        Boolean isNotifyWare = true;
        // add by wg 20190322 应根据订单类型进行处理，如果是店铺订单则直接发websocket通知管理员处理，如果是用户订单则通知店铺处理
        if (odsTeamIntentDto.getIntentType() == 1) {  // 用户订单
            MsgNotificationBody msg = new MsgNotificationBody();
            msg.setTitle("退款/退货申请");
            msg.setContent("订单" +intentId + "申请退款/退货，请处理");
            msg.setTime(new Date());
            msg.setReceiveType((byte) 1);
            msg.setOrderType((byte) 1);
            msg.setMsgType("orderMsg");
            Long shopId = odsTeamIntentDto.getShopId();
            List<Long> list = new ArrayList<>();
            list.add(shopId);
            List<ShopInfoDto> shopInfoByShopIds = smcFeignApi.getShopUserIdByShopIds(list);
            // mod by wg 20190518 改成只有云顶店铺配送的商品才通知店铺，由店铺去处理退款
//            if (shopInfoByShopIds != null && shopInfoByShopIds.size() != 0) {
            if (odsTeamIntentDto.getShippingType() == 3 && shopInfoByShopIds != null && shopInfoByShopIds.size() != 0) {
                msg.setOrderType((byte) 3);
                isNotifyWare = false;
                System.out.println(shopInfoByShopIds.get(0).getUserId().toString());
                opcSendNotifyFeignApi.sendnotify(shopInfoByShopIds.get(0).getUserId().toString(), "退款/退货申请", JSON.toJSONString(msg), 1);
                opcSendNotifyFeignApi.sendnotify(shopInfoByShopIds.get(0).getUserId().toString(), "退款/退货申请", "订单" + intentId + "申请退款，请处理", 0);
            }
        }


        if (isNotifyWare) {
            // 通知管理员处理
            Map map = new HashMap();
            map.put("MessageType", "findWarehouseAdmin");
            map.put("shopIds", odsTeamIntentDto.getShopId().toString());
            if (odsTeamIntentDto.getWarehouseId() != null) {
                map.put("warehouseIds", odsTeamIntentDto.getWarehouseId().toString());
            }
            map.put("body", "通知仓库管理员，有退款/退货申请需要审核");
            RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();
            rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
            rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_WMC);
            rabbitMetaMessage.setPayload(JSON.toJSONString(map));
            try {
                rabbitSender.send(rabbitMetaMessage);
            } catch (Exception e) {
                log.error("rabbitSender.send()调用异常");
            }
        }

        return WrapMapper.ok();
    }
}
